//
//  HttpUtils.m
//  接口测试
//
//  Created by 叶子韬韬 on 2017/4/17.
//  Copyright © 2017年 叶子韬韬. All rights reserved.
//

#import "HttpUtils.h"
#import "AFNetworking.h"
@implementation HttpUtils

/**
 下载文件

 @param str 要下载文件的名称
 @param successBack 成功回调
 @param failcallback 失败回调
 */
+(void)downLoadFileWith:(NSString *)str WithSuccess:(SuccessCallBack)successBack andFailBack:(FailCallBack)failcallback{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    // 创建管理者对象
    AFURLSessionManager *manger = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:configuration];
    // 确定请求的URL
    NSURL *url = [NSURL URLWithString:@"Http://localhost:8088/day10/download"];
    //创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod =@"post";
    NSString *Str = [NSString stringWithFormat:@"name=%@",str];
    request.HTTPBody = [Str dataUsingEncoding:NSUTF8StringEncoding];
    // 下载任务
    //下载任务
    NSURLSessionDownloadTask *task = [manger downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //打印下下载进度
        NSLog(@"下载速度：%lf",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //强制转换NSURLResponse
        NSHTTPURLResponse *HttpResponse = (NSHTTPURLResponse *)response;
        //获取响应头信息字典
        NSDictionary *dict = HttpResponse.allHeaderFields;
        NSString *content = dict[@"Content-Disposition"];
        //获取文件类型
        NSString *filename = [content substringFromIndex:19];
        //设置下载路径，通过沙盒获取缓存地址，最后返回NSURL对象
        NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        filePath = [NSString stringWithFormat:@"%@/%@",filePath,filename];
        return [NSURL fileURLWithPath:filePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if (error) {
            failcallback(error.description);
        }else{
            successBack(filePath);
        }

    }];
    //开始启动任务
    [task resume];

}

/**
 上传文件

 @param img 参数one
 @param successBack 成功回调
 @param failcallback 失败回调
 */
+(void)upLoadFileWith:(UIImage *)img WithSuccess:(SuccessCallBack)successBack andFailBack:(FailCallBack)failcallback{
    
    NSString *url = @"Http://localhost:8088/day1701/UpLoadTwo";
    
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                        @"text/html",
                                                        @"image/jpeg",
                                                        @"image/png",
                                                        @"application/octet-stream",
                                                        @"text/json", nil];
    
    NSDictionary *dict = @{@"username":@"wqwqwq"};
    
    NSURLSessionDataTask *task = [manger POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *imageData =UIImageJPEGRepresentation(img,1);
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat =@"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        
        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:imageData
                                    name:@"file"
                                fileName:fileName
                                mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"%@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error.description);
        
    }];
    
    //开始启动任务
    [task resume];
    
    
    
    
    
    
}
@end
